package com.zzy.controller;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * 生产者
 */
@RestController
@RequestMapping("productor")
public class ProductorController {

    @RequestMapping("/test")
    public Object test(){
        return System.currentTimeMillis();
    }

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    static String topic_ = "my-replication-topic";
    //http://localhost:8181/productor/send?message=11123123
    @RequestMapping ("/send")
    @ResponseBody
    public boolean send(@RequestParam String message) throws Exception{
       // ProducerRecord<K, V> producerRecord = new ProducerRecord(topic, data);
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic_, message.getBytes(StandardCharsets.UTF_8));
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                System.err.println("my-replication-topic - 生产者 发送消息失败：" + throwable.getMessage());
            }
            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                System.out.println("my-replication-topic - 生产者 发送消息成功：" + stringObjectSendResult.toString());
            }
        });
        return true;
    }




}
